package com.quectel.mobile.controller.partybuilding;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.func.LambdaUtil;
import com.quectel.constant.core.partybuilding.PartyBuildingPlanConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.core.module.partybuilding.dto.PartyPersonDto;
import com.quectel.core.module.partybuilding.service.PartyOrganizationService;
import com.quectel.core.module.partybuilding.service.PartyPersonService;
import com.quectel.core.module.partybuildingtask.dto.PartyBuildingPlanDto;
import com.quectel.core.module.partybuildingtask.dto.PartyBuildingPlanTaskDto;
import com.quectel.core.module.partybuildingtask.service.PartyBuildingPlanService;
import com.quectel.core.module.partybuildingtask.service.PartyBuildingPlanTaskService;
import com.quectel.mobile.controller.BaseController;
import com.quectel.mobile.util.SessionHolder;
import com.quectel.mobile.vo.partybuilding.PartyBuildingPlanTaskSubmitReq;
import com.quectel.util.common.JacksonUtils;
import com.quectel.util.common.Page;
import com.quectel.util.common.Request;
import com.quectel.util.common.Response;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 在这里编写说明
 *
 * @author: bob
 * @email: bob.yu@quectel.com
 * @date: 2023-06-13 13:58:00
 */
@RestController
@RequestMapping("partyBuildingPlanTask")
@Tag(name = "PartyBuildingPlanTaskController", description = "智慧党建-党建任务相关api")
public class PartyBuildingPlanTaskController extends BaseController {

    @DubboReference
    private PartyOrganizationService partyOrganizationService;
    @DubboReference
    private PartyPersonService partyPersonService;
    @DubboReference
    private PartyBuildingPlanService partyBuildingPlanService;
    @DubboReference
    private PartyBuildingPlanTaskService partyBuildingPlanTaskService;


    private static final Byte ALL = 1;
    private static final Byte UN_COMPLETE = 2;
    private static final Byte COMPLETED = 3;
    private static final String EXEC_STATUSES = "execStatuses";


    /**
     * 查看详情
     *
     * @param planId
     * @return
     */
    @GetMapping("infoPlan/{planId}")
    @Operation(summary = "查询详情")
    public Response<PartyBuildingPlanDto> infoPlan(@PathVariable("planId") Long planId) {
        SessionHolder.checkMobileUser();
        SessionHolder.checkPartyPerson();

        PartyPersonDto partyPerson = Objects.requireNonNull(SessionHolder.getLoginMobileUserSession()).getPartyPerson();
        Map<String, Object> params = new HashMap<>();
        Request request = Request.configParams(params);

        request.getParams().put(LambdaUtil.getFieldName(PartyBuildingPlanTaskDto::getTenantId), partyPerson.getTenantId());
        request.getParams().put(LambdaUtil.getFieldName(PartyBuildingPlanTaskDto::getExecUserId), partyPerson.getId());
        request.getParams().put(LambdaUtil.getFieldName(PartyBuildingPlanTaskDto::getPlanId), planId);

        if (partyBuildingPlanTaskService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        PartyBuildingPlanDto partyBuildingPlanDto = partyBuildingPlanService.selectCacheById(planId);

        return Response.<PartyBuildingPlanDto>ok().wrap(partyBuildingPlanDto);
    }


    /**
     * 全部：显示全部状态；待参加：未签到的所有状态；已参加：已签到的所有状态；
     *
     * @param queryRange
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("list")
    @Operation(summary = "党建活动分页查询列表")
    public Response<Page<PartyBuildingPlanTaskDto>> list(
            @Parameter(description = "查询范围1全部2待完成3已完成") @RequestParam Byte queryRange,
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        SessionHolder.checkMobileUser();
        SessionHolder.checkPartyPerson();
        PartyPersonDto partyPerson = Objects.requireNonNull(SessionHolder.getLoginMobileUserSession()).getPartyPerson();
        Map<String, Object> params = new HashMap<>();
        Request request = Request.configParams(params);

        request.getParams().put(LambdaUtil.getFieldName(PartyBuildingPlanTaskDto::getTenantId), partyPerson.getTenantId());
        request.getParams().put(LambdaUtil.getFieldName(PartyBuildingPlanTaskDto::getExecUserId), partyPerson.getId());


        if (queryRange.equals(UN_COMPLETE)) {
            request.getParams().put(LambdaUtil.getFieldName(PartyBuildingPlanTaskDto::getExecStatus), PartyBuildingPlanConstants.TaskStatus.UNCOMPLETED.getStatus());
        } else if (queryRange.equals(COMPLETED)) {
            request.getParams().put(LambdaUtil.getFieldName(PartyBuildingPlanTaskDto::getExecStatus), PartyBuildingPlanConstants.TaskStatus.COMPLETED.getStatus());
        } else if (queryRange.equals(ALL)) {
            request.getParams().put(EXEC_STATUSES, Arrays.asList(PartyBuildingPlanConstants.TaskStatus.COMPLETED.getStatus(), PartyBuildingPlanConstants.TaskStatus.UNCOMPLETED.getStatus()));
        }


        int totalCount = partyBuildingPlanTaskService.queryTotal(request.getParams());
        List<PartyBuildingPlanTaskDto> list = null;
        if (totalCount > 0) {
            list = partyBuildingPlanTaskService.queryList(params);

        } else {
            list = new ArrayList<>();
        }
        Page<PartyBuildingPlanTaskDto> page = new Page<>(request.getPageNo(), request.getPageSize(), totalCount, list);
        return Response.<Page<PartyBuildingPlanTaskDto>>ok().wrap(page);
    }

    /**
     * 查看详情
     *
     * @param id
     * @return
     */
    @GetMapping("info/{id}")
    @Operation(summary = "查询详情")
    public Response<PartyBuildingPlanTaskDto> info(@PathVariable("id") Long id) {
        SessionHolder.checkMobileUser();
        SessionHolder.checkPartyPerson();

        PartyPersonDto partyPerson = Objects.requireNonNull(SessionHolder.getLoginMobileUserSession()).getPartyPerson();
        Map<String, Object> params = new HashMap<>();
        Request request = Request.configParams(params);

        request.getParams().put(LambdaUtil.getFieldName(PartyBuildingPlanTaskDto::getTenantId), partyPerson.getTenantId());
        request.getParams().put(LambdaUtil.getFieldName(PartyBuildingPlanTaskDto::getExecUserId), partyPerson.getId());
        request.getParams().put(LambdaUtil.getFieldName(PartyBuildingPlanTaskDto::getId), id);

        if (partyBuildingPlanTaskService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        PartyBuildingPlanTaskDto partyBuildingPlanTaskDto = partyBuildingPlanTaskService.selectById(id);
        if(partyBuildingPlanTaskDto!=null){
            PartyBuildingPlanDto partyBuildingPlanDto = partyBuildingPlanService.selectCacheById(partyBuildingPlanTaskDto.getPlanId());
            partyBuildingPlanTaskDto.setPartyBuildingPlan(partyBuildingPlanDto);
        }

        return Response.<PartyBuildingPlanTaskDto>ok().wrap(partyBuildingPlanTaskDto);
    }


    /**
     * 查看详情
     *
     * @param buildingPlanTaskSubmitReq
     * @return
     */
    @PostMapping("submit")
    @Operation(summary = "查询详情")
    public Response<PartyBuildingPlanTaskDto> submit(@RequestBody @Validated PartyBuildingPlanTaskSubmitReq buildingPlanTaskSubmitReq) {
        SessionHolder.checkMobileUser();
        SessionHolder.checkPartyPerson();

        PartyPersonDto partyPerson = Objects.requireNonNull(SessionHolder.getLoginMobileUserSession()).getPartyPerson();
        Map<String, Object> params = new HashMap<>();
        Request request = Request.configParams(params);

        request.getParams().put(LambdaUtil.getFieldName(PartyBuildingPlanTaskDto::getTenantId), partyPerson.getTenantId());
        request.getParams().put(LambdaUtil.getFieldName(PartyBuildingPlanTaskDto::getExecUserId), partyPerson.getId());
        request.getParams().put(LambdaUtil.getFieldName(PartyBuildingPlanTaskDto::getId), buildingPlanTaskSubmitReq.getTaskId());

        if (partyBuildingPlanTaskService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        PartyBuildingPlanTaskDto partyBuildingPlanTaskDto = partyBuildingPlanTaskService.selectById(buildingPlanTaskSubmitReq.getTaskId());
        if(partyBuildingPlanTaskDto ==null){
            return Response.error("任务不存在");
        }
        PartyBuildingPlanDto partyBuildingPlanDto = partyBuildingPlanService.selectCacheById(partyBuildingPlanTaskDto.getPlanId());
        if(partyBuildingPlanDto ==null){
            return Response.error("任务不存在");
        }

        //未开始
        Date now = new Date();
        //未开始
        if (now.before(DateUtil.beginOfDay(partyBuildingPlanTaskDto.getDate())) || now.before(partyBuildingPlanDto.getStartTime())) {
            return Response.error("任务未开始");
        }

        //已结束
        if (now.after(DateUtil.endOfDay(partyBuildingPlanTaskDto.getDate()))|| now.after(partyBuildingPlanDto.getEndTime())) {
            return Response.error("任务已结束");
        }

        if (PartyBuildingPlanConstants.TaskStatus.COMPLETED.getStatus().equals(partyBuildingPlanTaskDto.getExecStatus())) {
            return Response.error("任务已完成，无须再次提交成果");
        }
        partyBuildingPlanTaskDto.setExtFiles(JacksonUtils.toJsonString(buildingPlanTaskSubmitReq.getExtFiles()));
        partyBuildingPlanTaskDto.setExecStatus(PartyBuildingPlanConstants.TaskStatus.COMPLETED.getStatus());
        partyBuildingPlanTaskDto.setCompleteTime(new Date());
        partyBuildingPlanTaskDto.setRemark(buildingPlanTaskSubmitReq.getRemark());

        partyBuildingPlanTaskService.updateById(partyBuildingPlanTaskDto);

        return Response.<PartyBuildingPlanTaskDto>ok();
    }

}
